package rsj.api;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.netty.example.BusinessHandler;
import com.rlyy.aibase.netty.server.NettyHttpServer;
import com.rlyy.aibase.os.work.WorkFactory;
import com.rlyy.aibase.view.type.OsType_Enum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import static rsj.api.MainUtil.isInteger;

public class Main {

	private static final Logger logger = LoggerFactory.getLogger(Main.class);

	public static int runPort = 9090;	/**
	 * 文件名为KEY 文件绝对路径为VALUE
	 */
	private static final HashMap<String,String> confFilesPath = new HashMap<>();

	static {
		// 默认配置文件对应
		confFilesPath.put("rsjConf.properties", "rsjConf.properties");
		confFilesPath.put("rsjdb.properties", "rsjdb.properties");

	}

	public static void main(String[] args) {
		// TODO
		//  1.数据库连接失败，项目启动停止
		//  2.
		// 2.redis url 初始化

		parseArgs2LoadConfPath(args);

		// 检查端口占用
		checkPortIsCanUse(runPort);


		//PropUtils.loadFile(getConfResource("rsjConf.properties"));
		//PostgresqlConn.loadFile(getConfResource("rsjdb.properties"));

		//JedisUtil.setNetUrl(PropUtils.getProperties("redisUrl"));

		//// 3.job 启动
		//doSchedulerJob();

		startNetty(args);

	}
	//
	//private static void doSchedulerJob() {
	//	try {
	//		//QuartzManager.sched(1L, "*/10 * * * * ?", new DoUpStatusJob());
	//		//QuartzManager.sched(2L, "0 */1 * * * ?", new DoUpBilJob());
	//	} catch (SchedulerException e) {
	//		logger.error("DoUpStatusJob start error !", e);
	//		throw new RuntimeException("DoUpStatusJob 启动失败 !", e);
	//	}
	//}

	private static void startNetty(String[] args) {
		if (WorkFactory.getStatus() != OsType_Enum.RUN.getOsType()) {
			WorkFactory.start(Config.class.getName());
		}

		try{
			NettyHttpServer.run(runPort, BusinessHandler.class);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private static void checkPortIsCanUse(int runPort) {
		if(MainUtil.isLocalPortUsing(runPort)){
			throw new RuntimeException("端口已经被占用！runPort:" + runPort);
		}
	}

	private static void parseArgs2LoadConfPath(String[] args) {
		// 默认读取jar包配置文件
		if(args == null || args.length == 0) return;
		// 一个参数时，配置端口号或配置路径（默认配置文件jar包内）
		if(args.length == 1) parseOneParamConf(args[0]);
		// 两个参数，第一个配置文件，第二个端口
		if(args.length == 2) parseTwoParamConf(args);
	}

	private static void parseOneParamConf(String arg0){
		if(isInteger(arg0)){
			runPort = Integer.parseInt(arg0);
		} else {
			loadConfByFileAbsoluPath(arg0);
		}
	}

	private static void parseTwoParamConf(String[] args){
		String arg0 = args[0];
		String arg1 = args[1];
		if(!new File(arg0).exists()){
			throw new IllegalArgumentException("第一个配置参数只能是配置文件或配置文件路径，配置文件不存在！");
		}
		if(!isInteger(arg1)){
			throw new IllegalArgumentException("第二个配置参数只能是端口号！");
		}

		loadConfByFileAbsoluPath(arg0);
		runPort = Integer.parseInt(arg1);
	}

	private static void loadConfByFileAbsoluPath(String arg1) {
		confFilesPath.clear();
		List<File> allDirectoryFiles = MainUtil.getAllDirectoryFiles(arg1);
		if(allDirectoryFiles.size() == 0){
			logger.error("------------------配置文件目录下没有配置文件------------------");
		}
		allDirectoryFiles.forEach(file -> {
			confFilesPath.put(file.getName(),file.getAbsolutePath());
		});
		logger.error("confFilesPathMap:{}", JSON.toJSONString(confFilesPath));
	}

	public static String getConfResource(String confFileKey){
		return confFilesPath.get(confFileKey);
	}
}
